﻿
//Morgan Hansen
//
//last update 4/15/2010
// Final.......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using MySql.Data.MySqlClient;
using System.Data;
using System.Windows.Forms;

namespace Controller
{
    class CurrentData
    {
        private VineyardBlock vineyardBlock;
        private byte soilMoisture;
        private double airTemp;
        private BlackBox blackbox;
        private bool waterStatus;
        private DateTime timeRecorded;
        private NetworkStream clientStream; //added --change Design Doc//done
        MySqlConnection conn;//added --change Design Doc//done
        private byte prevSoilMoisture;//added --change Design Doc//done
        private double prevAirTemp;//added --change Design Doc//done
        private bool prevWaterStatus;//added --change Design Doc//done

        public CurrentData(BlackBox b, NetworkStream stream)
        {

            string connectionString = "datasource=localhost;username=tara;password=tarapass;database=vino";
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand command = connection.CreateCommand();
            MySqlDataReader Reader = null;
            command.CommandText = "SELECT tblcurrentdata.SoilMoisture, tblcurrentdata.AirTemperature, tblcurrentdata.VineyardBlockID, tblcommand.CommandFlag FROM tblcurrentdata LEFT JOIN tblcommand on tblcurrentdata.BlackBoxID = tblcommand.BlackBoxID WHERE tblcurrentdata.BlackBoxID = " + b.GetBoxID().ToString() + " ORDER BY CurrentDataID DESC LIMIT 1";

            try
            {
                connection.Open();
                Reader = command.ExecuteReader();
            
            while (Reader.Read())
            {
                prevSoilMoisture = Convert.ToByte(Reader.GetValue(0));
                prevAirTemp = Convert.ToDouble(Reader.GetValue(1));
                prevWaterStatus = Convert.ToBoolean(Reader.GetValue(3));
                vineyardBlock = new VineyardBlock(Convert.ToInt32(Reader.GetValue(2)));
            }
            connection.Close();
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            soilMoisture = prevSoilMoisture;
            airTemp = prevAirTemp;
            blackbox = b;
            waterStatus = prevWaterStatus;
            clientStream = stream;
        }

        /// <summary>
        /// Author: Morgan Hansen & Ray
        /// This function polls the blackbox for data and 
        /// sets all vineyard data values. if the values 
        /// have changed from previous readings then this 
        /// function will update the Database 
        /// </summary>
        /// <returns></returns>
        public bool Compare()
        {
            byte[] blackboxRe = PollBlackBox(); //polls blackbox for data

            if ((blackboxRe[0] == 255) && (blackboxRe[1] == 255))
            {
                SetAirTemp(blackboxRe[2], blackboxRe[3], blackboxRe[4]);
                SetSoilMoisture(blackboxRe[5]);
                SetWaterStatus(blackboxRe[6]);
                SetTimeRecorded(DateTime.Now);
            }
            else if ((blackboxRe[0] == 255) && ((blackboxRe[1] == 0) || (blackboxRe[1] == 1)) && (blackboxRe[3] != 0) && (blackboxRe[4] != 0))
            {
                {
                    SetAirTemp(blackboxRe[1], blackboxRe[2], blackboxRe[3]);
                    SetSoilMoisture(blackboxRe[4]);
                    SetWaterStatus(blackboxRe[5]);
                    SetTimeRecorded(DateTime.Now);
                }
            }
            else 
            { return false; } //corrupt packet

            if ((prevSoilMoisture != soilMoisture) || (prevAirTemp != airTemp)) //|| (prevWaterStatus != waterStatus))
            {
                prevSoilMoisture = soilMoisture;
                prevAirTemp = airTemp;
                //prevWaterStatus = waterStatus;

                try //setting the database
                {
                    conn = new MySqlConnection("datasource=localhost;username=tara;password=tarapass;database=vino");
                    conn.Open();

                    MySqlCommand mycmd = new MySqlCommand("UPDATE tblcurrentdata SET CurrentDataID = NULL, VineyardBlockID = '" + vineyardBlock.blockID.ToString() + "', SoilMoisture = '" + soilMoisture.ToString() + "', AirTemperature = '" + airTemp.ToString() + "', TimeRecorded = '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", timeRecorded) + "' WHERE BlackBoxID = '" + blackbox.GetBoxID() + "'", conn);
                    mycmd.ExecuteNonQuery();

                    conn.Close();

                }//try
                catch (MySqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }//catch
                return true;
            }//if
            return false;
        }//Compare

        /// <summary>
        /// Author: Morgan Hansen
        /// polls BlackBox for data
        /// </summary>
        /// <returns>blackbox readings</returns>
        private byte[] PollBlackBox() //add to Design Doc
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] buffer;
            byte[] blackboxRe = new byte[7];

            buffer = encoder.GetBytes("fff"); //polling
            clientStream.Write(buffer, 0, buffer.Length);//sending poll command
            clientStream.Flush();
            clientStream.Read(blackboxRe, 0, 7);
            return (blackboxRe);
        }//pollBlackBox

        public double GetAirTemp()
        {
            return (airTemp);
        }

        public void SetAirTemp(byte signBit, byte whole, byte fract)
        {
            if (signBit == 0)
            { airTemp = ((whole + (fract * .01))); }
            else if (signBit == 1)
            { airTemp = (-1 * (whole + (fract * .01))); }
            else
            { airTemp = 999; }
        }

        public byte GetSoilMoisture()
        {
            return (soilMoisture);
        }

        public void SetSoilMoisture(byte mos)
        {
            soilMoisture = mos;
        }

        public bool GetWaterStatus()
        {
            return (waterStatus);
        }

        public void SetWaterStatus(byte stat)
        {
            if (stat == 0)
                waterStatus = false;
            else if (stat == 1)
                waterStatus = true;
        }

        public void SetWaterStatus(bool stat) //overloaded for bools
        {
            waterStatus = stat;
        }

        public int GetVineyardBlockID()
        {
            return (vineyardBlock.GetBlockID());
        }

        public bool SetVineyardBlockID(int block)  // may need to change in the Design Doc
        {
            vineyardBlock.blockID = block;
            return (true);  //may need try catch
        }

        public DateTime GetTimeRecorded()
        {
            return (timeRecorded);
        }

        public bool SetTimeRecorded(DateTime date)
        {
            timeRecorded = date;  //may need try catch;
            return (true);
        }

        public BlackBox GetBlackBox()
        {
            return (blackbox);
        }



    }//class
}//namespace
